﻿var action_provincial = "/report/prealarm/province.do"; //Integer indicatorType, String iname, String years, Integer page, Integer pageSize
var allField="/indicator/type/all.do" //---------------加载领域信息
var allCity="/area/allCity.do" //--------------加载地市级信息

var page=1;
var pageSize=1000;

//清除图形and表格数据
function clearData(){
		$("#view_containerzhuzi").html('');   //清空图形
		$("#view_containerzhuzi").height("0px");
		$("#view_containerzhuzi").width("0px");
		$("#view_columnar").html('');   //清空图形
		$("#view_columnar").height("0px");
		$("#view_columnar").width("0px");
		$('#tt').datagrid({data:[]});
}
	
//数据显示每年的达标率
function checkChangeImage(){
	var yeares = document.getElementsByName("year");
	var year = "";
	var yearList = [];
	for (var i = 0; i < yeares.length; i++) {
		if (yeares[i].checked) {
			yearList.push(yeares[i].value);
			year += yeares[i].value + ",";
		}
	}
    var indicatorType= $('#Field_com').combobox("getValue");          //领域编号
	$.get(action_provincial, {"indicatorType": indicatorType,"years": year,"page":page,"pageSize":pageSize,"formsid":1}, function (data) {
		if(data.code==200){
				data = data["data"].results;
				if(data==''||data==null||data==undefined||data==[]||data=='[]'){
					clearData();
					return;
				}
		//------------------------------------------------------------统计出每一年的各种达标情况的指标个数START
				var color_Data = [];   
				for (var j = 0; j < yearList.length; j++) {
					var years_Data = {};
					var red = 0;
                    var orange = 0;
					var yellow = 0;
					var blue = 0;
					var green = 0;
					for (var i = 0; i < data.length; i++) {
						var value = data[i][yearList[j]];
						var showlevel = value.split("_")[3];
						 /*
		                     10  红色#ff0000  预期难以达标
		                     20  橙色#FF9933  达标困难
		                     30  黄色#ffff00  当年未达标经努力预期可达标
		                     40  浅绿#039dea  达到当年标准
		                     50  深绿#009966  提前达标
	                     */
	                    if (Number(showlevel) == 10) {
	                        red++;
	                    }
	                    else if (Number(showlevel) == 20) {
	                        orange++;
	                    }
	                    else if (Number(showlevel) == 30) {
	                        yellow++;
	                    }
	                    else if (Number(showlevel) == 40) {
	                        blue++;
	                    }
	                    else if (Number(showlevel) == 50) { 
	                        green++;
	                    }
	                    else {
	                        continue;
	                    }
					}
					years_Data["year"] = yearList[j];
	                years_Data["red"] = red;
	                years_Data["orange"] = orange;
	                years_Data["yellow"] = yellow;
	                years_Data["blue"] = blue;
	                years_Data["green"] = green;
	                color_Data[j] = years_Data;
				}
		//--------------------------------------------------------------------------------统计出每一年的各种达标情况的指标个数END	
		//--------------------------------------------------------------------------------饼图数据封装加载饼图START
				//饼图数据封装
            var series = ["提前达标", "达到当年标准", "当年未达标经努力预期可达标", "达标困难", "预期难以达标"];
            var seriesData = [];
            var yearsData = [];
            var data_red = [];
            var data_orange = [];
            var data_yellow = [];
            var data_blue = [];
            var data_green = [];
            for (var i = 0; i < color_Data.length; i++) {
                data_red.push(color_Data[i].red);
                data_orange.push(color_Data[i].orange);
                data_yellow.push(color_Data[i].yellow);
                data_blue.push(color_Data[i].blue);
                data_green.push(color_Data[i].green);
                yearsData.push(color_Data[i].year);
            }

            var series_data_green = {"name": "提前达标", "type": "line", 'stack': '总量', "data": data_green};
            var series_data_blue = {"name": "达到当年标准", "type": "line", 'stack': '总量', "data": data_blue};
            var series_data_yellow = {"name": "当年未达标经努力预期可达标", "type": "line", 'stack': '总量', "data": data_yellow};
            var series_data_orange = {"name": "达标困难", "type": "line", 'stack': '总量', "data": data_orange};
            var series_data_red = {"name": "预期难以达标", "type": "line", 'stack': '总量', "data": data_red};

            seriesData.push(series_data_green);
            seriesData.push(series_data_blue);
            seriesData.push(series_data_yellow);
            seriesData.push(series_data_orange);
            seriesData.push(series_data_red);

            var reportResults = [];
            for (var i = 0; i < color_Data.length; i++) {
                var reportResult = {};
                reportResult["year"] = color_Data[i].year;    //循环年份
                var dataResult = [];
                dataResult[0] = {"name": series[0], "value": color_Data[i].green}
                dataResult[1] = {"name": series[1], "value": color_Data[i].blue}
                dataResult[2] = {"name": series[2], "value": color_Data[i].yellow}
                dataResult[3] = {"name": series[3], "value": color_Data[i].orange}
                dataResult[4] = {"name": series[4], "value": color_Data[i].red}
                reportResult["data"] = dataResult;
                reportResults[i] = reportResult;
            }

            series_ = series;         	  //图例数组
            reportResults = reportResults;  //饼图数据
            seriesData = seriesData;        //折线图数据
            yearsData = yearsData;          //折线图x轴年份数组

            showImage(series_, reportResults, (yearsData.length - 1), seriesData, yearsData);	//饼图、柱状图
            //----------------------------------------------------------------------------------饼图数据封装加载饼图END
            //----------------------------------------------------------------------------------datagrid数据加载START
            var sourceData = [];    //表格数据封装
            var advance = {};
            advance["controlState"] = "提前达标(个)";
            var barely = {};
            barely["controlState"] = "达到当年标准(个)";
            var makeRely = {};
            makeRely["controlState"] = "当年未达标经努力预期可达标(个)";
            var unBarely = {};
            unBarely["controlState"] = "达标困难";
            var seriousUnBarely = {};
            seriousUnBarely["controlState"] = "当预期难以达标";
            var targetRate = {};
            targetRate["controlState"] = "当年达标率(%)";
            for (var i = 0; i < yearList.length; i++) {
                var targetCount = data_green[i] + data_blue[i];
                var sum = data_green[i] + data_blue[i] + data_yellow[i] + data_red[i] + data_orange[i];
                advance[yearList[i]] = data_green[i];
                barely[yearList[i]] = data_blue[i];
                makeRely[yearList[i]] = data_orange[i];
                unBarely[yearList[i]] = data_yellow[i];
                seriousUnBarely[yearList[i]] = data_red[i];
                if (sum == 0) {
                    targetRate[yearList[i]] = 0;
                } else {
                    targetRate[yearList[i]] = Number((targetCount / sum) * 100).toFixed(2);
                }
            }
            sourceData.push(advance);
            sourceData.push(barely);
            sourceData.push(makeRely);
            sourceData.push(unBarely);
            sourceData.push(seriousUnBarely);
            sourceData.push(targetRate);
            var reportShowColumns = [];
            for (var i = 0; i < yearList.length; i++) {
                var c = {
                    title: yearList[i] + '年', field: yearList[i], width: 180, align: 'center',
                    formatter: function (value, row, index) {
                        return value;
                    }
                };
                reportShowColumns.push(c);
            }
            $('#tt').datagrid({
                width: '100%',
                height: 200,
                frozenColumns: [[
                    {field: 'controlState', title: '达标状态', width: 400}
                ]],
                columns: [reportShowColumns],
                singleSelect: true,// 是否单选
                loadMsg: '数据加载中,请稍后......',
                rownumbers: true,
                data: sourceData,
                rowStyler: function (index, row) {    //给对应数据加背景颜色
                    var controlState = row.controlState;
                    if (controlState == "当年达标率(%)") {
                        return 'font-weight:bold;';
                    }
                }
            });
            //-------------------------------------------------------------------------------------datagrid数据加载END
        } else {
            clearData();
        }
    }, "json");
}
var series_ = [];
var serieses = [];
var seriesData = [];//折线图数据数组
var dataLength = 0;

//饼图出图,折线出图
function showImage(series_, reportResults, index, seriesData, yearsData) {
    var field = $('#Field_com').combobox("getText");          //领域
    // field = field == '全部' ? '全部领域-' : (field + '领域-');
    $("#view_containerzhuzi").width($("#tabDiv").width()-40);
    var myChart = echarts.init(document.getElementById('view_containerzhuzi'));
    for (var i = 0; i < reportResults.length; i++) {
        var series = {};
        series["name"] = reportResults[i].year;
        series["type"] = 'pie';
        series["radius"] = '50%';
        series["center"] = ["50%", "50%"];
        series["data"] = reportResults[i].data;
        serieses[i] = series;
    }
    dataLength = serieses.length;
    var series = serieses[index];
    // 指定图表的配置项和数据
    var option = {
        title: {
            text: field + series.name + '年监测指标达标情况占比',
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        toolbox: {
            show: true,
            orient: 'vertical',
            y: '10%',
            itemSize: 24,
            feature: {
                mark: {show: true},
                dataView: {show: false, readOnly: false},
                restore: {show: true},
                saveAsImage: {show: true}
            }
        },
        legend: {
            x: 'center',
            y: 'bottom',
            data: series_
        },
        color: ['#009966', '#039dea', '#ffff00', '#FF9933', '#ff0000'],
        calculable: true,
        series: [
            {
                name: series.name,
                type: series.type,
                radius: series.radius,
                center: series.center,
                data: series.data,
                itemStyle: {
                    normal: {
                        label: {
                            show: true,
                            formatter: function (params) {
                                return (params.percent - 0) + '%';
                            },
                            textStyle: {
                                color: '#000'
                            }
                        },
                        labelLine: {show: true}
                    }
                }
            }
        ]
    };
    myChart.setOption(option);

    var zr = myChart.getZr();

    var icon0 = new echarts.graphic.Circle({
        shape: {r: 20},
        style: {
            text: '<',
//		        fill: '#eee'
            fill: '#dbdbdb'
        },
        position: [20, $("#view_containerzhuzi").height() / 2]
    });

    var icon1 = new echarts.graphic.Circle({
        shape: {r: 20},
        style: {
            text: '>',
            fill: '#dbdbdb'
        },
        position: [$("#view_containerzhuzi").width() - 20, $("#view_containerzhuzi").height() / 2]
    });

    var group = new echarts.graphic.Group();
    group.add(icon0);
    group.add(icon1);
    zr.add(group);


    icon0.on('click', function () {
        index -= 1;
        if (index < 0) {
            index += dataLength;
        }
        showImage(series_, reportResults, index, seriesData, yearsData);
    });
    icon1.on('click', function () {
        index = (index + 1) % dataLength;
        showImage(series_, reportResults, index, seriesData, yearsData);
    });

    $("#view_columnar").width($("#tabDiv").width()-40);
    var myChart_z = echarts.init(document.getElementById('view_columnar'));
    // 指定图表的配置项和数据
    option2 = {
        title: {
            text: field + '监测指标达标情况走势分析',
            left: 'center'
        },
        legend: {
            x: 'center',
            y: 'bottom',
            data: series_
        },
        tooltip: {
            trigger: 'axis'
        },
        toolbox: {
            show: true,
            orient: 'vertical',
            y: '10%',
            itemSize: 24,
            feature: {
                mark: {show: true},
                myTool1: {
                    show: true,
                    title: '切换为面积图',
                    icon: 'image:///resources/images/lineStack.png', //图标
                    onclick: function () {
                        for (var a = 0; a < option2.series.length; a++) {
                            option2.xAxis[0].boundaryGap = false;
                            option2.series[a].type = "line"
                            option2.series[a].areaStyle = {normal: {}};
                        }
                        myChart_z.setOption(option2);
                        for (var d = 0; d < option2.series.length; d++) {
                            delete  option2.series[d].itemStyle
                        }
                    }
                },
                myTool2: {
                    show: true,
                    title: '切换为折线图',
                    icon: 'image:///resources/images/line.png', //图标
                    onclick: function () {
                        for (var a = 0; a < option2.series.length; a++) {
                            option2.xAxis[0].boundaryGap = true;
                            option2.series[a].type = "line"
                            option2.series[a].areaStyle = {};
                        }
                        myChart_z.setOption(option2);
                    }
                },
                myTool3: {
                    show: true,
                    title: '切换为柱状图',
                    icon: "M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7",
                    onclick: function () {
                        for (var a = 0; a < option2.series.length; a++) {
                            option2.xAxis[0].boundaryGap = true;
                            option2.series[a].type = "bar"
                        }
                        myChart_z.setOption(option2);
                    }
                },
                magicType: {show: true, type: ['stack', 'tiled']},
                restore: {show: true},
                saveAsImage: {
                    show: true,
                    title: '保存为图片',
                    type: 'png',
                    lang: ['点击保存']
                }
            }
        },
        calculable: true,
        xAxis: [
            {
                type: 'category',
                boundaryGap: true,
                data: yearsData
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: seriesData,
        label: {
            normal: {
                show: true,
                textStyle: {color: '#000'}
            }
        },
        color: ['#009966', '#039dea', '#ffff00', '#FF9933', '#ff0000']
    };
    myChart_z.setOption(option2);


    window.onresize = function () {
       // onresizes();              //各容器自适应
        showImage(series_, reportResults, index, seriesData, yearsData);
//					myChart.resize();         //饼图自适应 myChart_z.resize();       //柱状图自适应
    }
}

//加载领域信息下拉列表
function loadField(){
	$.getJSON(allField,{'formsid':1}, function (json) {
		if(!json.success){
			 $.messager.alert('提示',json.massage);
			 return;
		}
			// json.data.unshift({
			// 	id : -1 ,
			// 	name : "全部",
			// 	sname : "全部"
			// });
			$('#Field_com').combobox({
				method : 'GET',
				async : false,
				data : json.data,
				editable : false,
				valueField : 'id',
				textField : 'name',
				onLoadSuccess : function() { // 数据加载完毕事件
					var a = $('#Field_com').combobox('getData');
					if (a.length > 0) {
						$("#Field_com").combobox('select', a[0].id);
					}
					
				},
				onSelect:function () {
					checkChangeImage();
					
				}
			})
		
		},
		'json');
	
}

var CRUD = {
		queryList: function () {
		    loadField();    //加载领域下拉列表
		}
};


$(document).ready(function () {
	$('#view_chart').panel({    
			title:"图形列表"
	});
	$('#tabDiv').tabs({
		height:450,
	    onSelect:function(title,index){
			if(index==0){
				var time= setTimeout(function(){
					checkChangeImage();
				},10);
			}else if(index==1){
				var time= setTimeout(function(){
					checkChangeImage();
				},10);
			}
	    }
	});
	$("#tabDiv").width($("#content").width()-20);
	CRUD.queryList();
});


//复选框点击事件
function checkyears(rec){
	   checkChangeImage();
}

//前端导出excel
function exportexcel() {
    var grid = $("#tt");
    var rows=grid.datagrid("getRows");					  //获得表格行数据
    var name='省级监测指标达标率分析'
    var colums_all=grid.datagrid("options").columns;      		     //获得表格的所有列不包括冻结列
    var colums_frozen= grid.datagrid("options").frozenColumns;       // 获取冻结列
    var columses=[];
    var columss=[];
    columss.push(colums_frozen[0][0]);
    for (var i = 0; i < colums_all[0].length; i++) {
    	columss.push(colums_all[0][i]);
	}
    columses[0]=columss;
    var obj = $.ExportExcelDlg({
        HeadInfo: columses,    //表头栏
        RowInfo: rows,		   //数据航
        FooterInfo: grid.datagrid("getFooterRows"),
        RowStart: 2,		   //导出行位置
        ColumStart: 2,		   //导出列位置
        SheetName: name,
        MainTitle: { Displayname: name, Alignment: 'Center' },
        SaveName: name,
        Swf: 'ExportExcel.swf'
    });
    obj.ExportExcelDlg('open');
}
